package com.example.smartstart.controller;

import com.example.smartstart.entity.MapPoint;
import com.example.smartstart.entity.Student;
import com.example.smartstart.model.MyResponseData;
import com.example.smartstart.model.Result;
import com.example.smartstart.service.IMapPointService;
import com.example.smartstart.service.impl.MapPointServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.stereotype.Controller;

/**
 * <p>
 *  前端控制器
 * </p>
 *
 * @author dlx
 * @since 2024-07-22
 */
@RestController
@RequestMapping("mapPoint/")
public class MapPointController {

    @Autowired
    private IMapPointService iMapPointService;

    // 创建或编辑点位
    @PostMapping("createOrUpdate")
    public Result createPoint(@RequestBody MapPoint mapPoint){
        Boolean result = iMapPointService.saveOrUpdate(mapPoint);
        if (result){
            return Result.success();
        }else {
            return Result.error("操作失败");
        }
    }

    // 分页查询所有点位
    @GetMapping("listByPage")
    public MyResponseData listByPage(MapPoint mapPoint){
        MyResponseData data = new MyResponseData();
        data.setErrorCode(0);
        data.setMessage("success");
        data.setArg1(iMapPointService.queryTotal(mapPoint));
        data.setList(iMapPointService.listByPage(mapPoint));
        return data;
    }

    // 管理员分页查询所有点位
    @GetMapping("adminListByPage")
    public MyResponseData adminListByPage(MapPoint mapPoint){
        MyResponseData data = new MyResponseData();
        data.setErrorCode(0);
        data.setMessage("success");
        data.setArg1(iMapPointService.adminQueryTotal(mapPoint));
        data.setList(iMapPointService.adminListByPage(mapPoint));
        return data;
    }

    // 删除点位
    @PostMapping("delete")
    public MyResponseData deleteMorePoint(Integer[] ids){
        int row = iMapPointService.deleteMorePoint(ids);
        MyResponseData data = new MyResponseData();
        if (row>=1){
            data.setErrorCode(0);
            data.setMessage("success");
            data.setArg1(row);
        }else {
            data.setErrorCode(1);
            data.setMessage("error");
        }
        return data;
    }

    // 用户打卡点位
    @PostMapping("checkIn")
    public Result checkIn(MapPoint mapPoint){
        try {
            iMapPointService.checkIn(mapPoint);
            return Result.success();
        } catch (MapPointServiceImpl.OutOfCheckinRangeException e){
            // 捕获OutOfCheckinRangeException并返回相应的响应
            return Result.error("您当前不在范围内，请前往打卡点打卡");
        }catch (RuntimeException e) {
            // 捕获其他运行时异常
            // 注意：这里可能会捕获到多种类型的运行时异常，你可以根据需要进一步细分处理
            // 但通常，对于未预料的异常，返回500 Internal Server Error是合适的
            // 你还可以选择记录这个异常到日志中
            return Result.error("服务器内部错误");
        }
    }
}
